<%@page import="java.sql.*"%>
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" errorPage="error.jsp"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style type="text/css">
h1{
color:red;
text-align:center;
}
.content{
border:3px solid red;
display:flex;
flex-direction:row;
gap:10px;
padding:10px;
}
.column{
border:1px solid gray;
white-space:nowrap;
padding:10px;
flex-grow:1;
text-align:left;
}
a{
color:gray;
text-decoration:none;
}
a:hover{
color:red;
text-decoration:underline;
}
</style>
<title>分页显示成语</title>
</head>
<body>
<h1>分页显示成语</h1><%
String stringPage=request.getParameter("page");
if(stringPage==null)stringPage="1";
int currentPage=Integer.parseInt(stringPage);
int n=25;
int columnCount=10;
int chengyuCountPerColumn=20;
int pageSize=columnCount*chengyuCountPerColumn;
int total=0;
Class.forName("com.mysql.cj.jdbc.Driver");
try(Connection cn=DriverManager.getConnection("jdbc:mysql://localhost:3306/db","root","12qwas");
		Statement st=cn.createStatement();
		ResultSet rs=st.executeQuery("select count(*) from chengyu");
	){
	rs.next();
	total=rs.getInt(1);
}
int maxPage=total/pageSize+(total%pageSize!=0?1:0);
//out.println("总的页面数="+maxPage);
if(currentPage<1)currentPage=1;
else if(currentPage>maxPage)currentPage=maxPage;
//out.println("当前页码="+currentPage);
int begin=currentPage-n;
int over=currentPage+n;
if(begin<1){
	over-=begin-1;
	if(over>maxPage)over=maxPage;
	begin=1;
}else if(over>maxPage){
	begin-=over-maxPage;
	if(begin<1)begin=1;
	over=maxPage;
}


%>

<div class='kuang'>
	<div class='nav'><%
	if(begin>1){
		out.println("<a href='?page=1'>首页</a> ");
	}
	for(int i=begin;i<=over;++i){
		if(i==currentPage){
			out.println("<b>"+i+"</b> ");
		}else{
			out.print("<a href='?page="+i+"'>"+i+"</a> ");
		}
	}
	if(over<maxPage){
		out.print("<a href='?page="+maxPage+"'>尾页</a> ");
	}
	
	
	%>
		
	</div>
	<div class='content'>
		<%
		try(Connection cn=DriverManager.getConnection("jdbc:mysql://localhost:3306/db","root","12qwas");
				PreparedStatement ps=cn.prepareStatement("select cy from chengyu limit ?,?");
				){
			ps.setInt(1,(currentPage-1)*pageSize);
			ps.setInt(2,pageSize);
			try(ResultSet rs=ps.executeQuery()){
				for(int col=0;col<columnCount;++col){
					out.println("\t\t<div class='column'>");
					for(int cy=0;cy<chengyuCountPerColumn;++cy){
						if(rs.next()){
							out.println("\t\t\t<p>"+rs.getString("cy")+"</p>");
						}else{
							out.println("\t\t\t<p>   </p>");	
						}
					}
					out.println("\t\t</div>");
				}
			}
		}
		
		
		
		
		%>
	</div>
</div>
</body>
</html>

